/// 本文件由reazhuang@outlook.com开发编写 *CodeMaid自动格式化*
/// 设计只绑定单个字段

using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Text;
using System.Text.Json;

namespace ReaWTM.LayuiHelper
{
	[HtmlTargetElement("wt:hidden", Attributes = REQUIRED_ATTR_NAME, TagStructure = TagStructure.WithoutEndTag)]
	public class HiddenTagHelper : BaseFieldTag
	{
		Type _modelType;
		protected override string GetDefaultValue()
		{
			if (Field.Model != null)
			{
				DefaultValue = JsonSerializer.Serialize(Field.Model, JsonOptions2);
			}
			if (string.IsNullOrEmpty(DefaultValue)) return "[]";

			if (!DefaultValue.StartsWith("["))
			{
				DefaultValue = $"[{DefaultValue}]";
			}
			return DefaultValue;
		}

		public override void Process(TagHelperContext context, TagHelperOutput output)
		{
			_modelType = Field.Metadata.ModelType;
			StringBuilder builder = new StringBuilder();
			output.TagName = "input";
			output.TagMode = TagMode.StartTagOnly;
			output.Attributes.Add("type", "hidden");

			builder.Append($@"
<script>
wtm.hidden_Render({{
id:'{Id}',
value:{GetDefaultValue()},
fieldName:'{GetName(context)}',
}});
</script>");
			output.PostElement.AppendHtml(builder.ToString());
			base.Process(context, output);
		}
	}
}